package com.forte.controller;

import java.util.Date;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.forte.cartdao.Cart;
import com.forte.cartdao.CartProduct;
import com.forte.cartservice.CartService;
import com.forte.exception.InvalidParameterException;
import com.forte.model.CartModel;
import com.forte.model.CartProductModel;
import com.forte.model.ProductModel;
import com.forte.model.ShoppingCustomerModel;
import com.forte.productdao.Product;
import com.forte.productservice.ProductService;
import com.forte.shoppingcustomer.ShoppingCustomerService;
import com.forte.shoppingcustomerdao.ShoppingCustomer;

@Controller
public class CartController {

	@Autowired
	CartService cartService;

	@Autowired
	ShoppingCustomerService customerService;

	@Autowired
	ProductService productService;

	Date currentDate = new Date();

	@RequestMapping(value = "/viewCart.do", method = RequestMethod.GET)
	public String viewCart(Model model) {
		ShoppingCustomer customer = customerService.findCustomerByEmail("email");
		int userId = customer.getCustomerId();
		model.addAttribute("cartproduct", cartService.findCartById(userId));
		return "cart";
	}
	
//	@RequestMapping(value = "/addtocart.do", method = RequestMethod.POST)
//	public String addProductToCart(Model model){
//		return "cart";
//	}

	@RequestMapping(value = "/addtocart.do", method = RequestMethod.POST)
	public String addProductToCart(@Valid @ModelAttribute("cart") CartProductModel cartPro,
			ProductModel product, int quantity, BindingResult result)
			throws InvalidParameterException {
		
		String returnPage = "";
		Cart findcart = cartService.findCartByCartId(cartPro.getCartId());
		ShoppingCustomer cust = customerService.findCustomerByCustomerId(findcart.getUserId());
		
		
		ShoppingCustomer findCustomer = customerService
				.findCustomerByEmail(cust.getEmail());
		
		Cart newCart = new Cart();
		newCart.setCookie("cookieId");
		newCart.setCreatedDate(currentDate);
		newCart.setUserId(findCustomer.getCustomerId());

		Product findProduct = productService.findProductByProductName(product
				.getProductName());
		Product newProduct = new Product();
		newProduct.setProductId(findProduct.getProductId());

		cartService.addToCart(newCart, newProduct, quantity);
		
		returnPage = "cart";
		
		return returnPage;
	}
}
